#include "stdafx.h"
#include "net/HTTPServerResponseImpl.hpp"
#include "net/HTTPServerRequestImpl.hpp"
#include "net/HTTPHeaderStream.hpp"
#include "net/HTTPRequest.hpp"
#include "net/HTTPResponse.hpp"
#include "net/HTTPFixedLengthStream.hpp"
#include "net/HTTPChunkedStream.hpp"
#include "net/HTTPStream.hpp"
#include "filesys/file.hpp"
using JHCPP::filesys::CFile;
#include "stream/streambuf.hpp"
#include "stream/StreamCopier.hpp"
#include "stream/FileStream.hpp"
using JHCPP::stream::CStreamCopier;
using JHCPP::stream::CFileInputStream;
using JHCPP::stream::CCountingOutputStream;
#include "stdlib/datetimeformat.hpp"
#include "stdlib/datetimeformatter.hpp"
using JHCPP::stdlib::CDateTimeFormat;
using JHCPP::stdlib::CDateTimeFormatter;

NET_NAMESPACE_BEGIN

CHTTPServerResponseImpl::CHTTPServerResponseImpl(CHTTPServerSession& session)
	: m_session(session),
	m_pRequest(0),
	m_pStream(0)
{
}

CHTTPServerResponseImpl::~CHTTPServerResponseImpl()
{
	delete m_pStream;
}

void CHTTPServerResponseImpl::sendContinue()
{
	CHTTPHeaderOutputStream hs(m_session);
	hs << getVersion() << " 100 Continue\r\n\r\n";
}

std::ostream& CHTTPServerResponseImpl::send()
{
	jh_assert (!m_pStream);

	if ((m_pRequest && m_pRequest->getMethod() == CHTTPRequest::HTTP_HEAD) ||
		getStatus() < 200 ||
		getStatus() == CHTTPResponse::HTTP_NO_CONTENT ||
		getStatus() == CHTTPResponse::HTTP_NOT_MODIFIED)
	{
		CCountingOutputStream cs;
		write(cs);
		m_pStream = new CHTTPFixedLengthOutputStream(m_session, cs.chars());
		write(*m_pStream);
	}
	else if (getChunkedTransferEncoding())
	{
		CHTTPHeaderOutputStream hs(m_session);
		write(hs);
		m_pStream = new CHTTPChunkedOutputStream(m_session);
	}
	else if (hasContentLength())
	{
		CCountingOutputStream cs;
		write(cs);
#if defined(JH_HAVE_INT64)	
		m_pStream = new CHTTPFixedLengthOutputStream(m_session, getContentLength64() + cs.chars());
#else
		m_pStream = new CHTTPFixedLengthOutputStream(m_session, getContentLength() + cs.chars());
#endif
		write(*m_pStream);
	}
	else
	{
		m_pStream = new CHTTPOutputStream(m_session);
		setKeepAlive(false);
		write(*m_pStream);
	}
	return *m_pStream;
}

void CHTTPServerResponseImpl::sendFile(const std::string& path, const std::string& mediaType)
{
	jh_assert (!m_pStream);

	CFile f(path);
	CTimeStamp dateTime    = f.getLastModified();
	CFile::FileSize length = f.getSize();
	set("Last-Modified", CDateTimeFormatter::format(dateTime, CDateTimeFormat::HTTP_FORMAT));
#if defined(JH_HAVE_INT64)	
	setContentLength64(length);
#else
	setContentLength(static_cast<int>(length));
#endif
	setContentType(mediaType);
	setChunkedTransferEncoding(false);

	CFileInputStream istr(path);
	if (istr.good())
	{
		m_pStream = new CHTTPHeaderOutputStream(m_session);
		write(*m_pStream);
		if (m_pRequest && m_pRequest->getMethod() != CHTTPRequest::HTTP_HEAD)
		{
			CStreamCopier::copyStream(istr, *m_pStream);
		}
	}
	else throw OpenFileException(path);
}

void CHTTPServerResponseImpl::sendBuffer(const void* pBuffer, std::size_t length)
{
	jh_assert (!m_pStream);

	setContentLength(static_cast<int>(length));
	setChunkedTransferEncoding(false);

	m_pStream = new CHTTPHeaderOutputStream(m_session);
	write(*m_pStream);
	if (m_pRequest && m_pRequest->getMethod() != CHTTPRequest::HTTP_HEAD)
	{
		m_pStream->write(static_cast<const char*>(pBuffer), static_cast<std::streamsize>(length));
	}
}

void CHTTPServerResponseImpl::redirect(const std::string& uri, HTTPStatus status)
{
	jh_assert (!m_pStream);

	setContentLength(0);
	setChunkedTransferEncoding(false);

	setStatusAndReason(status);
	set("Location", uri);

	m_pStream = new CHTTPHeaderOutputStream(m_session);
	write(*m_pStream);
}

void CHTTPServerResponseImpl::requireAuthentication(const std::string& realm)
{
	jh_assert (!m_pStream);

	setStatusAndReason(CHTTPResponse::HTTP_UNAUTHORIZED);
	std::string auth("Basic realm=\"");
	auth.append(realm);
	auth.append("\"");
	set("WWW-Authenticate", auth);
}

bool CHTTPServerResponseImpl::sent() const
{
	return m_pStream != 0;
}

void CHTTPServerResponseImpl::attachRequest(CHTTPServerRequestImpl* pRequest)
{
	m_pRequest = pRequest;
}

NET_NAMESPACE_END
